package com.fsd.admin.service.impl;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;

import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
import org.apache.log4j.Logger;

import com.google.gson.Gson;
import org.hibernate.Criteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Repository;
import com.fsd.core.service.impl.BaseServiceImpl;
import com.fsd.core.common.BusinessException;
import com.fsd.core.util.ParametersUtil;
import com.fsd.core.util.PdfUtil;
import com.fsd.admin.model.A_Employee;
import com.fsd.admin.model.Z_course;
import com.fsd.admin.service.Z_courseService;
import com.fsd.admin.dao.Z_courseDao;

@Repository("z_courseServiceImpl")
public class Z_courseServiceImpl extends BaseServiceImpl<Z_course, String> implements Z_courseService{
    
    private static final Logger log = Logger.getLogger(Z_courseServiceImpl.class);
    private String depict = "";
    
    @Resource(name = "z_courseDaoImpl")
	public void setBaseDao(Z_courseDao Z_courseDao) {
		super.setBaseDao(Z_courseDao);
	}
	
	@Resource(name = "z_courseDaoImpl")
	private Z_courseDao objectDao;
    
    /**
	 * 加载分页数据
	 * @param param
	 * @return
	 * @throws Exception
	 */
    @Override
	public ParametersUtil getObjectPageList(ParametersUtil param, A_Employee employee) throws Exception{
		Criteria c = objectDao.createCriteria();
		c.add(Restrictions.eq("f_deleted", "0"));
		c.addOrder(Order.asc("f_adddate"));
		if(param.getJsonData() != null && !"".equals(param.getJsonData())){
			Gson gs = new Gson();
			Map objectMap = gs.fromJson(param.getJsonData(), Map.class);
			if(objectMap.get("name") != null && !"".equals(objectMap.get("name"))){
				c.add(Restrictions.like("f_name", "%" + objectMap.get("name") + "%"));
			}
			if(objectMap.get("type") != null && !"".equals(objectMap.get("type"))){
				c.add(Restrictions.eq("f_typeid", objectMap.get("type")));
			}
		}
		return objectDao.findPager(param , c);
	}
    
    /**
	 * 编辑对象
	 * @param obj
	 * @param employee
	 * @throws Exception
	 */
    @Override
	public void save(String rootpath, Z_course obj, A_Employee employee) throws Exception{
        if(obj.getId() != null && !"".equals(obj.getId())){
//        	File file = new File("uploadfiles/projectfile/" + obj.getId() + ".pdf");//删除PDF文件
//    		if(file.exists()) {
//    			file.delete();
//    		}
            //修改
            Z_course old_obj = objectDao.get(obj.getId());
            old_obj.setF_typeid(obj.getF_typeid());
            old_obj.setF_name(obj.getF_name());
            old_obj.setF_teacher(obj.getF_teacher());
            old_obj.setF_score(obj.getF_score());
            old_obj.setF_period(obj.getF_period());
            old_obj.setF_count(obj.getF_count());
			old_obj.setF_xingqi(obj.getF_xingqi());
			old_obj.setF_jieci(obj.getF_jieci());
			old_obj.setF_semester(obj.getF_semester());
			old_obj.setF_remark(obj.getF_remark());
            old_obj.setF_platform(obj.getF_platform());
            old_obj.setF_url(obj.getF_url());
            old_obj.setF_abstract(obj.getF_abstract());
            old_obj.setF_collegename(obj.getF_collegename());
            old_obj.setF_site(obj.getF_site());
            old_obj.setF_propertyname(obj.getF_propertyname());
            old_obj.setF_wayname(obj.getF_wayname());
            old_obj.setF_sort(obj.getF_sort());
            
            old_obj.setF_lastupdatedate(this.getData());//设置修改日期
			old_obj.setF_updateemployeeid(employee.getId());//设置修改用户id
			old_obj.setF_updateemployeename(employee.getRealname());//设置修改用户姓名
//			doPdf(rootpath,old_obj,old_obj.getF_lastupdatedate());//生成修改后的PDF文件
            objectDao.update(old_obj);
        }else{
            //添加
            obj.setId(this.getUUID());//设置主键
			obj.setF_adddate(this.getData());//设置添加日期
			obj.setF_addemployeeid(employee.getId());//设置添加用户id
			obj.setF_state("ztty");//课程默认为启用状态
//			obj.setF_statusid("wsh");
//			obj.setF_statusname("未审核");
			obj.setF_addemployeename(employee.getRealname());//设置添加用户姓名
			obj.setF_deleted("0");//设置删除标志(0:正常 1：已删除)
//			doPdf(rootpath,obj,obj.getF_adddate());//生成PDF文件
			objectDao.save(obj);
        }
    }
    
    /**
	 * 删除对象
	 * @param parameters
	 * @throws Exception
	 */
    @Override
	public void delObject(ParametersUtil parameters, A_Employee employee) throws Exception{
		Gson gs = new Gson();
		Map objectMap = gs.fromJson(parameters.getJsonData(), Map.class);
		ArrayList<String> dir = (ArrayList<String>) objectMap.get("ids");
		String ids = "";
		for (String id : dir) {
			if (!ids.equals("")){
				ids += ",";
			}
			ids += "'" + id + "'";
		}
		String hql = "";
		objectDao.executeHql("update Z_course t set t.f_deleted = '1', t.f_lastupdatedate = '" + this.getData() + 
				"', t.f_updateemployeeid = '" + employee.getId() + "', t.f_updateemployeename = '" + employee.getRealname() + 
				"' where t.id in (" + ids + ")");
	}
    
    /**
	 * 根据ID加载对象
	 * @param parameters
	 * @return
	 * @throws Exception
	 */
    @Override
	public Z_course getObjectById(ParametersUtil parameters) throws Exception{
		Gson gs = new Gson();
		Map objectMap = gs.fromJson(parameters.getJsonData(), Map.class);
		if(objectMap.get("id") == null && "".equals(objectMap.get("id"))){
			throw new BusinessException(depict + "获取缺少ID参数!");
		}
		Z_course obj = objectDao.get(objectMap.get("id").toString());
		if(obj == null){
			throw new BusinessException(depict + "数据不存在!");
		}
		
		return obj;
	}

	/**
	 * 根据类型加载课程列表
	 * @param type
	 * @return
	 * @throws Exception
	 */
	public List<Z_course> getListByType(String type) throws Exception{
    	String sql  = "select * from Z_course where f_typeid = ? and f_deleted = ? and f_state = ?";
    	return objectDao.queryBySql1(sql, type, "0","ztqy");
	}

	/**
	 * 根据课程平台加载列表
	 * @param platform
	 * @return
	 * @throws Exception
	 */
	public List<Z_course> getListByPlatform(String platform) throws Exception{
		String sql = "select * from Z_course where f_platformcode = ? and f_deleted = ?";
		return objectDao.queryBySql1(sql, platform, "0");
	}

	@Override
	public Object getObjectMyPageList(ParametersUtil parameters, A_Employee loginUser) {
		Criteria c = objectDao.createCriteria();
		c.add(Restrictions.eq("f_deleted", "0"));
		c.addOrder(Order.asc("f_adddate"));
		c.add(Restrictions.eq("f_addemployeeid", loginUser.getId()));
		if(parameters.getJsonData() != null && !"".equals(parameters.getJsonData())){
			Gson gs = new Gson();
			Map objectMap = gs.fromJson(parameters.getJsonData(), Map.class);
			if(objectMap.get("type") != null && !"".equals(objectMap.get("type"))){
				c.add(Restrictions.eq("f_typeid", objectMap.get("type")));
			}
		}
		return objectDao.findPager(parameters , c);
	}

	@Override
	public void updateEnabledObject(ParametersUtil parameters, A_Employee employee) {
		Gson gs = new Gson();
		Map objectMap = gs.fromJson(parameters.getJsonData(), Map.class);
		ArrayList<String> idList = (ArrayList<String>) objectMap.get("ids");
		String ids = "";
		String oid = "";
		for (String id : idList) {
			if (!ids.equals("")){
				ids += ",";
			}
			ids += "'" + id + "'";
			oid = id;
		}
		boolean isEnabled = (Boolean) objectMap.get("isenabled");
		if (isEnabled) {
			objectDao.executeHql("update Z_course set f_state = 'ztqy' where id in (" + ids + ")");
		} else {
			objectDao.executeHql("update Z_course set f_state = 'ztty' where id in (" + ids + ")");
		}
	}
	
	@Override
	public void updateCheckedObject(ParametersUtil parameters, A_Employee employee) {
		Gson gs = new Gson();
		Map objectMap = gs.fromJson(parameters.getJsonData(), Map.class);
		ArrayList<String> idList = (ArrayList<String>) objectMap.get("ids");
		String ids = "";
		String oid = "";
		for (String id : idList) {
			if (!ids.equals("")){
				ids += ",";
			}
			ids += "'" + id + "'";
			oid = id;
		}
		objectDao.executeHql("update Z_course set f_statusid = 'tgsh',f_statusname='通过审核' ,f_reason = '' where id in (" + ids + ")");
	}
	
	/**
	 * 生成pdf方法
	 * @param rootpath
	 * @param obj
	 * @param date
	 * @throws Exception
	 */
    private void doPdf(String rootpath,Z_course obj,String date) throws Exception {
    	
    	String pdfurl = "uploadfiles/projectfile/" + obj.getId() + ".pdf";
		obj.setF_pdfurl(pdfurl);
		String tmpFile = rootpath + "uploadfiles/pdftemplate/create_course.pdf";
		String outFile = rootpath + pdfurl;
		//生成Word文件
		Map<String,Object> map= new HashMap<String,Object>();
        map.put("fill_3",obj.getF_name());
        map.put("fill_4",obj.getF_period());
        map.put("fill_5",obj.getF_score());
        if("cyi".equals(obj.getF_propertyid())) {
            map.put("ch1","√");
        }else if("cx".equals(obj.getF_propertyid())) {
        	map.put("ch2","√");
        }else {
        	map.put("ch3","√");
        }
        if("spoc".equals(obj.getF_wayid())) {
        	map.put("ch4","√");
        }else {
        	map.put("ch5","√");
        }
        map.put("fill_6",obj.getF_site());
        map.put("fill_1",obj.getF_teacher());
        map.put("fill_2",obj.getF_count());
        map.put("fill_7",obj.getF_collegename());
        map.put("fill_8",obj.getF_abstract());
        PdfUtil.createPdfByTemplate(map, tmpFile, outFile);
    }

	@Override
	public void saveMessage(Z_course obj, A_Employee loginUser) {
		Z_course old_obj = objectDao.get(obj.getId());
		old_obj.setF_statusid("jjsh");
		old_obj.setF_statusname("拒绝审核");
		old_obj.setF_reason(obj.getF_reason());
		objectDao.save(old_obj);
	}

	/**
	 * 导入课程
	 * @param rootPath
	 * @param f_url
	 * @throws Exception
	 */
	public void updateImportCourse(String rootPath, String f_url) throws Exception{
		try{
			if(f_url.indexOf(".xls") == -1 && f_url.indexOf(".xlsx") == -1){
				throw new BusinessException("仅支持导入Excel文件，请重新上传");
			}
			File file = new File(rootPath + "/" + f_url); //根据文件名创建一个文件对象
			if(file == null || !file.exists()){
				throw new BusinessException("导入Excel文件不存在");
			}
			Workbook wb = Workbook.getWorkbook(file); //从文件流中取得Excel工作区对象
			int size = wb.getSheets().length;//得到Sheet数量
			if(size == 0){
				throw new BusinessException("导入Excel文件格式错误，请检查");
			}
			Sheet sheet = wb.getSheet(0);//从工作区中取得页，取得这个对象的时候既可以用名称来获得，也可以用序号。
			for (int i = 2; i < sheet.getRows()-1; i++) {
				Cell[] cells = sheet.getRow(i);

				String name = cells[1].getContents();
				String ls = cells[2].getContents();
				String jj = cells[3].getContents();
				String xf = cells[4].getContents();
				String xs = cells[5].getContents();
				String xsrs = cells[6].getContents();
				String kkxy = cells[7].getContents();
				String xq = cells[8].getContents();
				String jc = cells[9].getContents();
				String kkdd = cells[10].getContents();
				String kkxq = cells[11].getContents();
				String bz = cells[12].getContents();
				Z_course course = new Z_course();
				course.setId(this.getUUID());
				course.setF_typeid("xxkc");
				course.setF_typename("线下课程");
				course.setF_statusid("tgsh");
				course.setF_statusname("通过审核");
				course.setF_adddate(this.getData());
				course.setF_addemployeeid("63404406fa98474faecc53c445a17cb1");
				course.setF_addemployeename("管理员15");
				course.setF_deleted("0");

				course.setF_name(name);
				course.setF_teacher(ls);
				course.setF_abstract(jj);
				course.setF_score(xf);
				course.setF_period(xs);
				course.setF_count(xsrs);
				course.setF_collegename(kkxy);
				course.setF_xingqi(xq);
				course.setF_jieci(jc);
				course.setF_site(kkdd);
				course.setF_semester(kkxq);
				course.setF_remark(bz);
				objectDao.save(course);
			}
		}catch (Exception e){
			e.printStackTrace();
			throw new BusinessException("导入Excel文件格式错误，请检查" + e.getMessage());
		}
	}
}
